import React, { useState } from 'react'
import { Card, Alert, Cascader, Col, message, Tabs } from 'antd'
import { getAllCate } from '../../app/goodscate'
import { getParamsAPI } from '../../app/params'
import './index.less'
import ParsmaTab from './components/ParsmaTab'

const { TabPane } = Tabs
export default function Params () {
    // 初始化商品分类数据
    const [allGoodsCate, setAllGoodsCate] = useState([])
    // 商品分类默认选中项
    const [defaultCate, setDefaultCate] = useState([])
    // 初始化选中的分类id
    const [cateId, setCateId] = useState(0)
    // 初始化参数列表
    const [paramsList, setParamsList] = useState([])
    // 控制增加参数按钮的显示与禁用
    const [btnDisable, setBtnDisable] = useState(true)
    // 获取商品分类
    const getGoodsCate = async () => {
        const { data, meta } = await getAllCate()
        if(meta.status !== 200) return message.error('获取商品分类失败')
        setAllGoodsCate(data)
    }
    // 获取参数列表
    const getParamsList = async (id=cateId, sel='many') => {
        const { meta, data } = await getParamsAPI(id, sel)
        if(meta.status !== 200) return message.error('获取参数列表失败')
        console.log(data)
        data.forEach((item, index) => item.index = index)
        setParamsList(data)
    }
    // 级联框改变
    const onCascaderChange = values => {
        if(values.length < 3) {
            setDefaultCate([])
            setParamsList([])
            setBtnDisable(true)
            return
        }
        setBtnDisable(false)
        setCateId(values[values.length - 1])
        setDefaultCate(values)
        getParamsList(values[values.length - 1])
    }
    // tabs标签发生改变触发的事件
    const tabChangeCallBack = key => {
        const attrSel = key === '1' ? 'many' : 'only'
        getParamsList( cateId, attrSel)
    }
    return (
        <Card className="params-container">
            <Alert message="注意：只允许为第三级分类设置相关参数！" type="warning" showIcon />
            {/* 商品分类 */}
            <Col>
            选择商品分类：<Cascader
                options={allGoodsCate}
                expandTrigger="hover"
                placeholder="请选择"
                allowClear={false}
                value={defaultCate}
                notFoundContent="加载中..."
                onChange={onCascaderChange}
                onFocus={getGoodsCate}
                fieldNames={{
                    label:'cat_name',
                    value:'cat_id'
                }}
                   />
            </Col>
            {/* 参数选择 */}
            <Tabs defaultActiveKey="1" onChange={tabChangeCallBack}>
                <TabPane tab="动态参数" key="1">
                <ParsmaTab attrSel="many" catId={cateId} btnDisable={btnDisable} paramsList={paramsList} getParamsList={getParamsList} />
                </TabPane>
                <TabPane tab="静态属性" key="2">
                <ParsmaTab attrSel="only" catId={cateId} btnDisable={btnDisable} paramsList={paramsList} getParamsList={getParamsList} />
                </TabPane>
            </Tabs>
        </Card>
    )
}